package com.cn.wanxi.jwt.config;

import com.cn.wanxi.jwt.filter.JwtAuthenticationTokenFilter;
import com.cn.wanxi.jwt.result.RestAuthenticationEntryPoint;
import com.cn.wanxi.jwt.result.RestfulAccessDeniedHandler;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpMethod;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @ClassName WebSecurityConfigure
 * @Description Spring Security配置类
 * @Author JiJiang
 * @Date 2022/9/27 14:32
 * @Version 1.0
 */
@Configuration
// 这个注解很重要，如果没有这个注解，那么Controller里的方法将不受约束，只要登录成功就能访问，而无视是否有改权限
//开启权限认证
@EnableGlobalMethodSecurity(prePostEnabled = true)
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {


    @Autowired
    private UserDetailsService userDetailsService;

    @Autowired
    private JwtAuthenticationTokenFilter jwtAuthenticationTokenFilter;

    @Autowired
    private RestAuthenticationEntryPoint restAuthenticationEntryPoint;

    @Autowired
    private RestfulAccessDeniedHandler restfulAccessDeniedHandler;

    @Override
    protected void configure(HttpSecurity http) throws Exception {

//                第二步:我们用我们自己的数据库数据来完成权限验证
        // 关闭跨域和csrf保护
        http.cors().and().csrf().disable()
                .sessionManagement()//允许配置会话管理
                //Spring Security永远不会创建一个HttpSession，也永远不会使用它获取SecurityContext
                .sessionCreationPolicy(SessionCreationPolicy.STATELESS)//
                .and()
                .authorizeRequests()
                .antMatchers("/", "/user/login", "/user/test").permitAll()// index 放行
                .antMatchers(HttpMethod.OPTIONS).permitAll()//options 方法的请求放行
                .anyRequest().authenticated()// 其它请求要认证
                .and()
                // 这一步，告诉Security 框架，我们要用自己的UserDetailsService实现类
                // 来传递UserDetails对象给框架，框架会把这些信息生成Authorization对象使用
                .userDetailsService(userDetailsService);
        // 过滤前,我们使用jwt进行过滤,
        // 表明自定义的 jwtAuthenticationTokenFilter 过滤器在 UsernamePasswordAuthenticationFilter之前执行
        //但是这里并未使用formLogin
        http.addFilterBefore(jwtAuthenticationTokenFilter, UsernamePasswordAuthenticationFilter.class);

        //添加自定义未授权和未登录结果返回
        //配置异常处理过滤拦截
        http.exceptionHandling()
                //如果抛出认证不通过异常则进入restfulAccessDeniedHandler
                //这里可以理解为使用自定义的 认证异常处理对象 替换了 框架原本的认证异常处理对象
                .accessDeniedHandler(restfulAccessDeniedHandler)
                //添加自定义的权限异常处理
                .authenticationEntryPoint(restAuthenticationEntryPoint);
    }


    /**
     * 这里配置密码加密方式，这样创建用户时，会对密码进行加密。而不是明文存储。
     *
     * @return
     */
    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    /**
     * @MethodName authenticationManagerBean
     * @Description 该Bean会调用authenticate方法，该方法需要一个Authentication类型的对象
     * @Param []
     * @Return org.springframework.security.authentication.AuthenticationManager
     **/
    @Bean
    @Override
    public AuthenticationManager authenticationManagerBean() throws Exception {
        return super.authenticationManagerBean();
    }

}
